package com.netease.ticket;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.NameValuePair;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

public class JavaScriptExecutor {

	private static Context cx;
	private static boolean bInit = false;
	private static Scriptable scope;
	
	public static void main(String[] args) throws Exception {
		//System.out.println(new JavaScriptExecutor().analyzeJS());
	}
	
	public static NameValuePair analyzeJS(String jsFile) throws Exception {
		
		if(!bInit){
			cx = ContextFactory.getGlobal().enterContext();
			scope = cx.initStandardObjects(null);
			cx.setOptimizationLevel(-1);
			cx.setLanguageVersion(Context.VERSION_1_5);
			String[] file = { "./js/env.rhino.1.2.js", "./js/jquery.js"  };
			for (String f : file) {
				evaluateJs(f);
			}
			bInit = true;
		}
		
		evaluateJs(jsFile);
		String step1 = (String) ScriptableObject.callMethod(scope, "gc", new Object[]{});
		String param[] = step1.split(":");
		ScriptableObject base32 = (ScriptableObject)ScriptableObject.getProperty(scope, "Base32");
		String encrypt = (String)ScriptableObject.callMethod(cx, base32, "encrypt", new Object[]{param[1],param[0]});
		String bin216 = (String)ScriptableObject.callMethod(scope, "bin216", new Object[]{encrypt});
		String encode32 = (String)ScriptableObject.callMethod(scope, "encode32", new Object[]{bin216});
		NameValuePair nvp = new NameValuePair(param[0], encode32);
		return nvp;
	}

	protected static void evaluateJs(String f) {
		try {
			FileReader in = null;
			in = new FileReader(f);
			cx.evaluateReader(scope, in, f, 1, null);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
